#!/usr/bin/env bash

SRC=`dirname $0`
PWD=`pwd`
PIGOBJS="$SRC/pigasus-types.o $SRC/formatstring.o $SRC/loadcsv.o $SRC/cast.o $SRC/serialization.o $SRC/common.o"
echo "Pig compiler"

PIGOUT="pig.out"

while getopts ":o:" opt; do
  case $opt in
    o)
      PIGOUT="$OPTARG"
      ;;
    *)
      ;;
  esac
done

# Compiling the object files is expensive, so check first
make -C $SRC -q
if [ $? != 0 ]
then
  echo "Building Pigasus object files"
  make -C $SRC -j
fi

# Compiling the grammar is easy, just do it every time...
make -C $SRC/grammar > /dev/null

# ${!#} is the last argument (i.e. source.pig)
$SRC/grammar/pigtrans < ${!#} > /dev/null
if [ $? != 0 ]
then
  echo "Error during parsing; exiting"
  exit 1
fi

cp $SRC/*.sh $PWD

g++ -o $PIGOUT -I$SRC -pthread pigMain.cc $SRC/*.o

for f in $( ls $PWD/*.cc )
do
  if [ `basename $f` == "pigMain.cc" ]
  then
    continue
  fi
  g++ -o `basename $f .cc`.out -I$SRC -pthread $f $PIGOBJS;
done
